package org.stbernardpreserve.learning.effectivejava.mutator;

import java.util.Collection;
import java.util.Date;
import java.util.EnumMap;
import java.util.LinkedList;
import java.util.Map;

import org.stbernardpreserve.learning.effectivejava.mutator.ELaundryMessage.ELaundryMessageType;

public enum ELaundryConsumerMessages {
	INSTANCE;
	private final Map<ELaundryMessageType, ELaundryMessage> eLaundryMessagesSet = new EnumMap<ELaundryMessageType, ELaundryMessage>(
			ELaundryMessageType.class);
	private final Collection<ELaundryMessageHistory> history = new LinkedList<ELaundryMessageHistory>();

	public void postNewMessage(ELaundryMessage message) {
		if (eLaundryMessagesSet.containsKey(message.getMessageType())) {
			history.add(new ELaundryMessageHistory(eLaundryMessagesSet
					.get(message.getMessageType())));
		}
		eLaundryMessagesSet.put(message.getMessageType(), message);
	}

	public Collection<ELaundryMessageHistory> getHistory() {
		Collection<ELaundryMessageHistory> copyOfHistory = new LinkedList<ELaundryMessageHistory>(
				history);
		return copyOfHistory;
	}

	private String getMessageText(ELaundryMessageType messageType )
	{
		if (eLaundryMessagesSet
				.containsKey(messageType)) {

			return eLaundryMessagesSet.get(messageType)
					.getText();
		} else
			throw new MessageDoesNotExistException(messageType);
		
	}
	public String getPromoMessage() {
		return getMessageText(ELaundryMessageType.PromotionalItem);
	}

	public String getNewsItemMessage() {
		return getMessageText(ELaundryMessageType.NewsItem);
	}
	
	public String getItemNoLongerAvailableMessage() {
		return getMessageText(ELaundryMessageType.ItemNoLongerAvailable);
	}


	public static class ELaundryMessageHistory {
		private final Date timeAddedToHistory;
		private final ELaundryMessage message;

		private ELaundryMessageHistory(ELaundryMessage message) {
			this.timeAddedToHistory = new Date();
			this.message = message;
		}

		public Date getTimeAddedToHistory() {
			return timeAddedToHistory;
		}

		public ELaundryMessage getMessage() {
			return message;
		}

	}
	
	@SuppressWarnings("serial")
	public static class MessageDoesNotExistException extends RuntimeException
	{
		public MessageDoesNotExistException(ELaundryMessageType messageType)
		{
			super(messageType.toString());
		}
	}
	

}
